package com.juqimiao.raccoon.commodity.command;

import com.juqimiao.linn.command.CommandExecutor;
import com.juqimiao.linn.command.CommandExecutorI;
import com.juqimiao.linn.exception.BusinessException;
import com.juqimiao.linn.utils.IdGeneratorI;
import com.juqimiao.raccoon.commodity.appobj.CategoryGroupAO;
import com.juqimiao.raccoon.commodity.constraints.OperationNewGroup;
import com.juqimiao.raccoon.commodity.domain.CategoryGroupFactory;
import com.juqimiao.raccoon.commodity.domain.category.CategoryGroup;
import com.juqimiao.raccoon.commodity.dto.AddCategoryGroupCmd;
import com.juqimiao.raccoon.commodity.repository.CategoryGroupRepository;
import com.juqimiao.raccoon.commodity.extension.CategoryGroupValidExtPt;
import com.juqimiao.linn.extension.ExtensionExecutor;
import com.juqimiao.linn.transfer.Response;
import com.juqimiao.linn.transfer.query.builders.ResponseBuilder;

import org.springframework.beans.factory.annotation.Autowired;

@CommandExecutor
public class AddCategoryGroupCmdExt implements CommandExecutorI<Response, AddCategoryGroupCmd> {


    private final ExtensionExecutor extensionExecutor;

    private final CategoryGroupRepository repository;

    private final IdGeneratorI generator;

    private final CategoryGroupFactory factory;

    @Autowired
    public AddCategoryGroupCmdExt(ExtensionExecutor extensionExecutor,
                               CategoryGroupRepository repository,
                               IdGeneratorI generator,
                               CategoryGroupFactory factory) {
        this.extensionExecutor = extensionExecutor;
        this.repository = repository;
        this.generator = generator;
        this.factory = factory;
    }

    @Override
    public Response execute(AddCategoryGroupCmd cmd) {
        Response response = null;


        extensionExecutor.executeVoid(CategoryGroupValidExtPt.class,
                cmd.getBusinessPoint(),
                extension -> extension.validate(cmd.getCategoryGroupAO(), OperationNewGroup.class));

        CategoryGroupAO groupAo = cmd.getCategoryGroupAO();
        CategoryGroup group = factory.createNew(
                groupAo.getName(),
                groupAo.getSpell(),
                groupAo.getGroupType(),
                groupAo.getScenario(),
                groupAo.getSubmitId(),
                groupAo.getSortOrder());

        if (group.getPolicy().hasSameName()) {
            throw new BusinessException("The Name cannot be same in CategoryType= "
                    + cmd.getCategoryGroupAO().getGroupType()
                    + " and Scenario= "
                    + cmd.getCategoryGroupAO().getScenario());
        }

        String msg = repository.insert(group);
        response = ResponseBuilder.builder().success(msg).build();
        return response;
    }

    private String generateId() {
        return generator.nextStrId();
        //Integer.toString(new Random().nextInt(10000));
    }
}
